from bcc import BPF

bpf_text = """
#include <uapi/linux/ptrace.h>

// 文件路径 到 read_write_class_id 的映射
#define NAME_MAX 255
struct filepath {
    char raw_str[NAME_MAX];
};
BPF_HASH(path_to_read_write_class_id, struct filepath, int);

// 进程 PID 到 read_write_class_id 的映射
BPF_HASH(pid_to_read_write_class_id, int, int);

// read_write_class_id 到 owner_class_id 的映射
BPF_HASH(class_id_to_owner_class_id, int, int);

// read_write_class_id 到 class_ids_can_read_this 的映射
BPF_HASH(class_ids_can_read_this, int, int);
BPF_HASH_OF_MAPS(class_id_to_ids_can_read_this, int, "class_ids_can_read_this");

// read_write_class_id 到 class_ids_can_write_this 的映射
BPF_HASH(class_ids_can_write_this, int, int);
BPF_HASH_OF_MAPS(class_id_to_ids_can_write_this, int, "class_ids_can_write_this");

// 全局配置
# define FLAG_RUNNING_ONCE 14
BPF_HASH(global_variable, u32, u32);

int syscall__execve(struct pt_regs *ctx,
    const char __user *filename,
    const char __user *const __user *__argv,
    const char __user *const __user *__envp)
{
    bpf_trace_printk("syscall__execve_start!\\n");
    u32 flag_running_once_key = FLAG_RUNNING_ONCE;
    u32 zero = 0;
    u32 one = 1;
    global_variable.insert(&flag_running_once_key, &zero);
    u32* flag_running_once = global_variable.lookup(&flag_running_once_key);
    if(flag_running_once != 0){
        if (*flag_running_once != 0){
            return 0;
        }
        else{
            global_variable.update(&flag_running_once_key, &flag_running_once_key);
        }
    }
    
    

    return 0;
}
"""
if __name__ == "__main__":
    b = BPF(text=bpf_text)
    execve_fnname = b.get_syscall_fnname("execve")
    b.attach_kprobe(event=execve_fnname, fn_name="syscall__execve")
    b.trace_print()